package com.web.dao.impl;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.web.dao.AbstractRepository;
import com.web.model.User;

@Repository("userRepository")
public class UserRepository implements AbstractRepository{
	
	@Autowired
    private MongoTemplate mongoTemplate;     
    

   @Override  
   public List<User> findAll() {   
       return getMongoTemplate().find(new Query(), User.class);     
 
   }  
  
   @Override  
   public void findAndModify(String id) {   
       getMongoTemplate().updateFirst(new Query(Criteria.where("id").is(id)), new Update().inc("age", 3),User.class);  
 
   }  
 
   @Override  
   public List<User> findByRegex(String regex) {   
        Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);     
         Criteria criteria = new Criteria("name").regex(pattern.toString());     
           return getMongoTemplate().find(new Query(criteria), User.class);     
 
   }  
  
   @Override  
   public User findOne(String id) {  
        return getMongoTemplate().findOne(new Query(Criteria.where("id").is(id)), User.class);     
 
   }  
 
   @Override  
   public void insert(User user) {  
       getMongoTemplate().insert(user);     
   }  
  
   @Override  
   public void removeAll() {  
       List<User> list = this.findAll();     
       if(list != null){     
           for(User user : list){     
               getMongoTemplate().remove(user);     
           }     
       }     
 
   }  
 
   @Override  
   public void removeOne(String id) {  
       Criteria criteria = Criteria.where("id").in(id);     
       if(criteria == null){     
            Query query = new Query(criteria);     
            if(query != null && getMongoTemplate().findOne(query, User.class) != null)     
                getMongoTemplate().remove(getMongoTemplate().findOne(query, User.class));     
       }     
 
   }  
 
   public MongoTemplate getMongoTemplate() {  
       return mongoTemplate;  
   }  
 
   public void setMongoTemplate(MongoTemplate mongoTemplate) {  
       this.mongoTemplate = mongoTemplate;  
   }  
 
}  
